/*
 * @Description: chanle实现队列
 * @Version: 1.0
 * @Author: biao.hu
 * @Date: 2021-10-29 14:29:55
 * @LastEditors: biao.hu
 * @LastEditTime: 2021-10-29 14:54:24
 */
package Queue

import "fmt"

type (
	ChanleQueue struct {
		Ch        chan int
		Length    int
		MaxLength int
	}
)

/**
 * @description: New一个ChanleQueue
 * @param {int} maxLength
 * @return {*ChanleQueue}
 */
func NewChanleQueue(maxLength int) *ChanleQueue {
	return &ChanleQueue{Ch: make(chan int, maxLength), Length: 0, MaxLength: maxLength}
}

/**
 * @description: push进队列
 * @param {int} val
 * @return {error}
 */
func (ch *ChanleQueue) Push(val int) error {
	if ch.Length == ch.MaxLength {
		fmt.Println("The maximum length has been reached, maxLength:", ch.MaxLength)
		return nil
	}
	ch.Ch <- val
	ch.Length++
	return nil
}

/**
 * @description: pop队列数据
 * @param {*}
 * @return {int}
 */
func (ch *ChanleQueue) Pop() int {
	if ch.Length > 0 {
		ch.Length--
		val := <-ch.Ch
		fmt.Print(val, " ")
		return val
	}
	panic("ch.Length is 0, nodata")
}

/**
 * @description: 该方法放进main方法里面执行
 * @param {*}
 * @return {*}
 */
func RunChanleQueue() {
	count := 10
	ch := NewChanleQueue(count)
	// 入队列
	for i := 0; i < count+1; i++ {
		ch.Push(i)
	}

	// 出队列
	for i := 0; i < count; i++ {
		ch.Pop()
	}
}
